#!/bin/sh
rm -f dist/m4b-tool* bin/*.log

if [ "$1" = "--with-plugins" ]; then
    echo "!!! WITH PLUGINS !!!";
    PHP_CODE="echo '';"
else
    PHP_CODE="try {\
    \$p = 'phar://'.realpath(__DIR__.'/dist/m4b-tool.phar').'/src/library/Command/Plugins/'; \
    \$f = new Phar(\$p);\
    foreach(\$f as \$file) {\
    unlink(\$file);\
    }\
    } catch(Throwable \$e) {}";
fi

[ -e ".composer-alias" ] && COMPOSER_ALIAS=$(xargs < .composer-alias)
[ "$COMPOSER_ALIAS" != "" ] && COMPOSER="$COMPOSER_ALIAS" || COMPOSER="$(which composer)"
if [ "$COMPOSER" = "" ]; then
    echo "composer required, but not installed"
    exit 1;
fi

$COMPOSER install --no-dev --optimize-autoloader --ignore-platform-reqs

# shellcheck disable=SC2164
php -d phar.readonly=off vendor/bin/box compile \
    && php -d phar.readonly=off -r "${PHP_CODE}" \
    && chmod +x dist/*.phar \
    && tar -C dist -czf dist/m4b-tool.tar.gz m4b-tool.phar \
    && cd dist \
    && zip m4b-tool.zip m4b-tool.phar \
    && cd -
$COMPOSER install
